<template>
  <div class="amap-page-container">
    <!-- <input type="text" v-model="selectkey" />
    <button v-on:click="req_post()">req_post</button> -->
    <div :style="{ width: '100%', height: '300px' }">
      <el-amap
        vid="amap"
        :plugin="plugin"
        :events="events"
        :zoom="zoom"
        class="amap-demo"
        :center="center"
        ref="map"
      >
        <el-amap-marker
          v-for="(marker, index) in markers"
          :position="marker"
          :key="index"
          :icon="icon"
        ></el-amap-marker>
        <el-amap-marker
          v-for="(item, index) in markersList"
          :key="index"
          :index="index"
          :position="item"
          :icon="icon"
          :content="content"
          :events="markerevents"
        ></el-amap-marker>
      </el-amap>
    </div>

    <div class="toolbar">
      <span v-if="loaded"> location: lng = {{ lng }} lat = {{ lat }} </span>
      <span v-else>正在定位</span>
    </div>
    <!-- <div v-on:click="req_post()">查询周边</div> -->
  </div>
</template>


<script>
import { Toast } from "vant";
import axios from "axios";
import { AMapManager, Geocoder, lazyAMapApiLoaderInstance } from "vue-amap";
export default {
  data() {
    const self = this;
    return {
      center: [112.436356, 34.68598],
      content:0,
      lng: 0,
      lat: 0,
      path: "",
      icon:'',
      zoom: 12,
      markers: [],
      markersList: [],
      selectkey: "",
      loaded: false,
      markerevents:{
        //标记事件
        click: this.markClick(), //标记点击触发
      },
      events: {
        init() {
          lazyAMapApiLoaderInstance.load().then(() => {
            self.initSearch();
            
            //self.$refs.map.$$getInstance().setFitView();
          });
        },
        // 点击获取地址的数据
        click(e) {
          // console.log(e)
          self.markers = [];
          let { lng, lat } = e.lnglat;
          self.lng = lng;
          self.lat = lat;
          self.center = [lng, lat];
          self.markers.push([lng, lat]);
           //self.icon="⚪"
          //self.markers.on('click',function(){console.log("dianji")});//绑定click事件
          // 这里通过高德 SDK 完成。
          let geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all",
          });
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === "complete" && result.info === "OK") {
              if (result && result.regeocode) {
                console.log(result.regeocode.formattedAddress);
                self.address = result.regeocode.formattedAddress;
                self.searchKey = result.regeocode.formattedAddress;
                self.$nextTick(() => {});
              }
            }
          });
        },
      },
      plugin: [
        {
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 100, //超过10秒后停止定位，默认：无穷大
          maximumAge: 10, //定位结果缓存0毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: "RB", //定位按钮停靠位置，默认：'LB'，左下角
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
          extensions: "all",
          pName: "Geolocation",
          events: {
            init(o) {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                console.log(result);
                if (result && result.position) {
                  self.lng = result.position.lng;
                  self.lat = result.position.lat;
                  self.center = [self.lng, self.lat];
                  self.$emit("my-address", self.center);
                  self.loaded = true;
                  self.$nextTick();
                }
              });
            },
          },
        },
        {
          
        }
      ],
    };
  },
  methods: {
     markClick() {
        this.content = '我是第' + (1+ 1) + '个Marker';
       //Toast("tishi");
    },
    initSearch() {
      //getMap
      let vm = this
                let map = this.AMapManager.getMap()
                AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
                    var poiPicker = new PoiPicker({
                        input: 'search',
                        placeSearchOptions: {
                            map: map,
                            pageSize: 10
                        },
                        suggestContainer: 'searchTip',
                        searchResultsContainer: 'searchTip'
                    })
                    vm.poiPicker = poiPicker
                    // 监听poi选中信息
                    poiPicker.on('poiPicked', function (poiResult) {
                        // console.log(poiResult)
                        let source = poiResult.source
                        let poi = poiResult.item
                        if (source !== 'search') {
                            poiPicker.searchByKeyword(poi.name)
                        } else {
                            poiPicker.clearSearchResults()
                            vm.markers = []
                            let lng = poi.location.lng
                            let lat = poi.location.lat
                            let address = poi.cityname + poi.adname + poi.name
                            vm.center = [lng, lat]
                            vm.markers.push([lng, lat])
                            vm.lng = lng
                            vm.lat = lat
                            vm.address = address
                            vm.searchKey = address
                        }
                    })
                })
    },
    req_post(list) {
      console.log(list)
      this.click(list);
    },
    click(list) {
      list.forEach((v) => {
        this.markersList.push(v.location.split(","));
        //this.icon="⚪";
      });
     
      let geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all",
      });
    },
  },
  mounted() {},
};
</script>

<style>
.amap-wrapper {
  width: 500px;
  height: 500px;
}
.amap-demo {
  height: 300px;
}
</style>